import { autoUpdater } from 'electron-updater'
import winUtil from './window-util'
import { BrowserWindow, ipcMain } from 'electron/main'

class UpdateUtil {
  constructor() {
    autoUpdater.autoDownload = false
    autoUpdater.autoInstallOnAppQuit = false
    autoUpdater.forceDevUpdateConfig = true
  }

  startCheckVersion(): void {
    autoUpdater.checkForUpdates()

    // C:\\Users\\54335\\AppData\\Local\\compress-updater\\pending\\compress-1.0.3-setup.exe
    // C:\\Users\\54335\\AppData\\Local\\Temp'

    let win: BrowserWindow

    autoUpdater.on('update-available', async (info) => {
      ipcMain.handle('update:info', async () => info)

      const path = await autoUpdater.downloadUpdate()

      console.log('下载路径', path)
      // 需要更新打开更新窗体
    })

    autoUpdater.on('download-progress', () => {
      // 存在blockmap文件则不会走这个回调，autoupdater会自动根据blockmap的文件自动合成一个包
      console.log('download-progress')
      // win.webContents.send('download:progress', progress)
    })

    autoUpdater.on('update-downloaded', () => {
      console.log('update-downloaded')
      win = winUtil.createUpdateWidow()

      win.webContents.on('did-fail-load', () => {
        win.webContents.send('update-downloaded')
      })
    })

    autoUpdater.on('update-not-available', (info) => {
      console.log('update-not-available', info)
    })

    ipcMain.on('quit:and:install', () => {
      autoUpdater.quitAndInstall()
    })
  }
}

export default new UpdateUtil()
